<template>
  <div class="page-content exhibition-detail">
    <!-- 页面头部 -->
    <div class="mb-6 flex justify-between items-center">
      <div>
        <h1 class="text-2xl font-bold">展品详情</h1>
        <p class="text-gray-500 mt-2">查看展品的详细信息</p>
      </div>
      <div class="flex gap-3">
        <el-button type="primary" @click="editExhibition">
          <el-icon class="mr-1"><Edit /></el-icon>编辑展品
        </el-button>
        <el-button @click="goBack">
          <el-icon class="mr-1"><Back /></el-icon>返回
        </el-button>
      </div>
    </div>

    <el-skeleton :loading="isLoading" animated>
      <template #template>
        <div class="grid grid-cols-1 md:grid-cols-3 gap-6">
          <div class="md:col-span-2">
            <el-skeleton-item variant="image" class="w-full h-300px rounded-lg" />
            <div class="flex space-x-2 mt-2">
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
              <el-skeleton-item variant="image" class="w-80px h-80px rounded-md" />
            </div>
          </div>
          <div>
            <el-skeleton-item variant="h3" class="w-1/2" />
            <el-skeleton-item variant="text" class="mt-4 w-4/5" />
            <el-skeleton-item variant="text" class="mt-4 w-3/5" />
            <el-skeleton-item variant="text" class="mt-4 w-full" />
          </div>
        </div>
      </template>

      <template #default>
        <el-row :gutter="24">
          <!-- 左侧展品信息 -->
          <el-col :md="16" :sm="24">
            <el-card shadow="hover" class="mb-6 overflow-hidden border-0 rounded-lg">
              <div class="exhibition-header flex justify-between items-start">
                <div>
                  <h2 class="text-xl font-semibold">{{ exhibitionDetail.name }}</h2>
                  <div class="flex items-center mt-2">
                    <div class="text-sm text-gray-500 flex items-center">
                      <el-icon class="mr-1"><Location /></el-icon>
                      {{ exhibitionDetail.location }} {{ exhibitionDetail.floor }}
                    </div>
                  </div>
                </div>
                <el-tag :type="getStatusType(exhibitionDetail.status || 1)" size="large">
                  {{ statusTextMap[exhibitionDetail.status || 1] }}
                </el-tag>
              </div>

              <!-- 展品图片 -->
              <div class="mt-4">
                <el-carousel
                  v-if="coverImage"
                  :interval="4000"
                  type="card"
                  height="400px"
                  :autoplay="true"
                  indicator-position="outside"
                  class="carousel-container"
                >
                  <el-carousel-item>
                    <el-image
                      :src="coverImage"
                      fit="cover"
                      class="w-full h-full rounded-lg object-cover"
                      @click="previewImage(0, [coverImage])"
                    >
                      <template #error>
                        <div class="image-error-slot">
                          <el-icon><Picture /></el-icon>
                        </div>
                      </template>
                    </el-image>
                  </el-carousel-item>
                </el-carousel>

                <div
                  v-else
                  class="placeholder-image flex items-center justify-center bg-gray-100 h-400px rounded-lg"
                >
                  <el-icon class="text-6xl text-gray-300"><Picture /></el-icon>
                </div>

                <!-- 相册预览 -->
                <div v-if="detailImages.length" class="image-gallery mt-4 grid grid-cols-5 gap-2">
                  <el-image
                    v-for="(img, index) in detailImages"
                    :key="index"
                    :src="img"
                    fit="cover"
                    class="gallery-thumbnail cursor-pointer h-80px rounded-md border-2 border-transparent hover:border-primary transition-all"
                    @click="previewImage(index, detailImages)"
                  />
                </div>
              </div>

              <!-- 展品介绍 -->
              <div class="mt-6">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                  <el-icon class="mr-2 text-primary"><InfoFilled /></el-icon>展品介绍
                </h3>
                <p class="text-gray-700 leading-relaxed whitespace-pre-line">
                  {{ exhibitionDetail.description }}
                </p>
              </div>

              <!-- 语音讲解 -->
              <div class="mt-6" v-if="audioGuide">
                <h3 class="text-lg font-medium mb-3 flex items-center">
                  <el-icon class="mr-2 text-primary"><Headset /></el-icon>语音讲解
                </h3>
                <div class="audio-guide p-4 bg-gray-50 rounded-lg">
                  <audio :src="audioGuide" controls class="w-full"></audio>
                </div>
              </div>
            </el-card>
          </el-col>

          <!-- 右侧信息栏 -->
          <el-col :md="8" :sm="24">
            <!-- 基本信息卡片 -->
            <el-card shadow="hover" class="mb-6 border-0 rounded-lg">
              <template #header>
                <div class="flex items-center">
                  <el-icon class="mr-2 text-primary"><Document /></el-icon>
                  <span class="font-medium">基本信息</span>
                </div>
              </template>

              <ul class="space-y-2">
                <li class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                  <span class="w-24 text-gray-500 flex-shrink-0">展品名称</span>
                  <span class="text-gray-800 flex-1">{{ exhibitionDetail.name }}</span>
                </li>
                <li class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                  <span class="w-24 text-gray-500 flex-shrink-0">展出位置</span>
                  <span class="text-gray-800 flex-1">{{ exhibitionDetail.location }}</span>
                </li>
                <li class="flex py-3 border-b border-gray-100 hover:bg-gray-50 transition-colors duration-200">
                  <span class="w-24 text-gray-500 flex-shrink-0">展示楼层</span>
                  <span class="text-gray-800 flex-1">{{ exhibitionDetail.floor }}</span>
                </li>
                <li class="flex py-3 hover:bg-gray-50 transition-colors duration-200">
                  <span class="w-24 text-gray-500 flex-shrink-0">展出状态</span>
                  <span class="text-gray-800 flex-1">{{ statusTextMap[exhibitionDetail.status || 1] }}</span>
                </li>
                <li class="flex py-3 hover:bg-gray-50 transition-colors duration-200">
                  <span class="w-24 text-gray-500 flex-shrink-0">编码</span>
                  <span class="text-gray-800 flex-1">{{ exhibitionDetail.itemNumber }}</span>
                </li>
              </ul>
            </el-card>
            <!-- 二维码 -->
            <el-card shadow="hover" class="mb-6 border-0 rounded-lg overflow-hidden">
              <template #header>
                <div class="flex items-center">
                  <el-icon class="mr-2 text-primary"><Document /></el-icon>
                  <span class="font-medium">二维码</span>
                </div>
              </template>
              <div class="flex flex-col items-center p-4">
                  <!-- <QrcodeVue
                    ref="qrcodeRef"
                    :value="qrValue"
                    :size="200"
                    level="H"
                    :eyeRadius="0"
                    render-as="canvas"
                    :margin="4"
                    background="#ffffff"
                    foreground="#000000"
                    :image-settings="qrImageSettings"
                  /> -->
                  <QrcodeVue
                  ref="qrcodeRef"
                  :value="`https://wuhansportpark.com/weixin/?id=${route.query.id}&type=activity&detailType=7`"
                  :size="200"
                  level="H"
                  render-as="svg" 
                />
                <el-button type="primary" class="mt-4" @click="downloadQRCode">
                  <el-icon class="mr-1"><Download /></el-icon>下载二维码
                </el-button>
              </div>
            </el-card>
          </el-col>
        </el-row>
      </template>
    </el-skeleton>

    <!-- 图片预览器 -->
    <el-image-viewer
      v-if="showViewer"
      :initial-index="viewerIndex"
      :url-list="viewerImages"
      @close="showViewer = false"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import {
  Edit,
  Back,
  Picture,
  InfoFilled,
  Document,
  Location,
  Headset,
  Download
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { ExhibitionItemVoduixiang } from '@/api/4a/types'
import { scenicExhibitionItemGetUsingPost } from '@/api/4a/zhanpinguanli'
import QrcodeVue from 'qrcode.vue'

const route = useRoute()
const router = useRouter()
const isLoading = ref(true)

const canvasimg = ref()
// 构造更健壮的二维码内容
const qrValue = computed(() => {
  const rawId = route.query.id
  const idStr = Array.isArray(rawId) ? rawId[0] : rawId
  const id = idStr ?? ''
  return `https://wuhansportpark.com/weixin/?id=${encodeURIComponent(String(id))}&type=activity&detailType=7`
})


const exhibitionDetail = ref<ExhibitionItemVoduixiang>({})

// 状态映射
const statusTextMap: Record<number, string> = {
  1: '展出中',
  2: '维护中',
  3: '已下架'
}

// 获取状态类型
const getStatusType = (status: number): 'success' | 'warning' | 'danger' | 'info' => {
  const typeMap: Record<number, 'success' | 'warning' | 'danger'> = {
    1: 'success',
    2: 'warning',
    3: 'danger'
  }
  return typeMap[status] || 'info'
}

// 图片数据处理
const coverImage = computed(() => {
  try {
    const coverImageData = JSON.parse(exhibitionDetail.value.coverImage || '[]')
    return coverImageData[0]?.path || ''
  } catch (e) {
    return ''
  }
})

const detailImages = computed(() => {
  try {
    const detailImagesData = JSON.parse(exhibitionDetail.value.detailImages || '[]')
    return detailImagesData.map((img: any) => img.path)
  } catch (e) {
    return []
  }
})

const audioGuide = computed(() => {
  try {
    const audioData = JSON.parse(exhibitionDetail.value.audioGuide || '[]')
    return audioData[0]?.path || ''
  } catch (e) {
    return ''
  }
})

// 图片预览器
const showViewer = ref(false)
const viewerIndex = ref(0)
const viewerImages = ref<string[]>([])

// 图片预览
const previewImage = (index: number, images: string[]) => {
  viewerIndex.value = index
  viewerImages.value = images
  showViewer.value = true
}

// 编辑展品
const editExhibition = () => {
  router.push(`/exhibition/edit?id=${route.query.id}`)
}

// 返回列表
const goBack = () => {
  router.back()
}

// 获取展品详情
const getExhibitionDetail = async () => {
  isLoading.value = true
  try {
    const rawId = route.query.id
    if (!rawId) {
      ElMessage.error('展品ID不能为空')
      return
    }

    const idStr = Array.isArray(rawId) ? rawId[0] : rawId
    const id = Number(idStr)
    if (Number.isNaN(id)) {
      ElMessage.error('展品ID格式不正确')
      return
    }

    const res = await scenicExhibitionItemGetUsingPost({ params: { id } })
    if (res.code === 0 && res.data) {
      exhibitionDetail.value = res.data
    } else {
      ElMessage.error(res.msg || '获取展品详情失败')
    }
  } catch (error) {
    exhibitionDetail.value = {
      name: '测试',
      status: 1,
      location: '测试',
      floor: '测试',
      description: '',
      coverImage: "[{\"path\":\"https://wuhansportpark.com/file/local-file/20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\",\"size\":\"3306\",\"name\":\"微信截图_20250623163949.png\",\"fileName\":\"20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\"},{\"path\":\"https://wuhansportpark.com/file/local-file/20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\",\"size\":\"3306\",\"name\":\"微信截图_20250623163949.png\",\"fileName\":\"20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\"}]",
      detailImages: "[{\"path\":\"https://wuhansportpark.com/file/local-file/20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\",\"size\":\"3306\",\"name\":\"微信截图_20250623163949.png\",\"fileName\":\"20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\"},{\"path\":\"https://wuhansportpark.com/file/local-file/20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\",\"size\":\"3306\",\"name\":\"微信截图_20250623163949.png\",\"fileName\":\"20250710/cdbb3e9cdcd74c6da434c8fe08ea127c微信截图_20250623163949.png\"}]",
      audioGuide: "[{\"path\":\"https://wuhansportpark.com/file/local-file/20250710/54b3f8b5a6774be7be337cd6326604e133.mp3\",\"size\":\"219939\",\"name\":\"33.mp3\",\"fileName\":\"20250710/54b3f8b5a6774be7be337cd6326604e133.mp3\"}]"
    }
    console.error('获取展品详情失败:', error)
    ElMessage.error('获取展品详情失败')
  } finally {
    isLoading.value = false
  }
}

const qrcodeRef = ref<{ $el: HTMLCanvasElement } | null>(null)


// 生成中心文字图片（用于覆盖在二维码中间）
const generateCenterTextImage = (text: string, width = 56, height = 56): string => {
  const canvas = document.createElement('canvas')
  canvas.width = width
  canvas.height = height
  const ctx = canvas.getContext('2d')
  if (!ctx) return ''

  // 背景圆角白底
  const radius = 10
  ctx.fillStyle = '#ffffff'
  ctx.beginPath()
  ctx.moveTo(radius, 0)
  ctx.lineTo(width - radius, 0)
  ctx.quadraticCurveTo(width, 0, width, radius)
  ctx.lineTo(width, height - radius)
  ctx.quadraticCurveTo(width, height, width - radius, height)
  ctx.lineTo(radius, height)
  ctx.quadraticCurveTo(0, height, 0, height - radius)
  ctx.lineTo(0, radius)
  ctx.quadraticCurveTo(0, 0, radius, 0)
  ctx.closePath()
  ctx.fill()
  // 外边框让元素更凸显
  ctx.strokeStyle = '#409EFF'
  ctx.lineWidth = 2
  ctx.stroke()

  // 文本
  ctx.fillStyle = '#000000'
  ctx.textAlign = 'center'
  ctx.textBaseline = 'middle'
  // 自适应字号（最多8字符）
  const len = (text || '').toString().length
  const fontSize = len <= 3 ? 22 : len <= 6 ? 18 : 16
  ctx.font = `bold ${fontSize}px system-ui, -apple-system, Segoe UI, Roboto, Arial`
  // 阴影增强可读性
  ctx.shadowColor = 'rgba(0,0,0,0.2)'
  ctx.shadowBlur = 4
  ctx.shadowOffsetX = 0
  ctx.shadowOffsetY = 1
  // 给文字描边提升对比
  ctx.lineWidth = 3
  ctx.strokeStyle = '#ffffff'
  ctx.strokeText(text || '', width / 2, height / 2)
  ctx.fillText(text || '', width / 2, height / 2)
  return canvas.toDataURL('image/png')
}

// 二维码中间覆盖的图片设置（展示展品ID）
const qrImageSettings = computed(() => {
  const centerText = String((exhibitionDetail.value as any)?.itemNumber || '')
  const src = generateCenterTextImage(centerText, 56, 56)
  return {
    src,
    width: 56,
    height: 56,
    excavate: true
  }
})

// 下载二维码（使用与页面完全相同的样式）
const downloadQRCode = () => {
  if (!qrcodeRef.value) return

  const svg = qrcodeRef.value.$el
  const serializer = new XMLSerializer()
  const svgStr = serializer.serializeToString(svg)
  const canvas = document.createElement('canvas')
  const ctx = canvas.getContext('2d')
  const img = new Image()

  img.onload = () => {
    canvas.width = img.width
    canvas.height = img.height
    ctx?.drawImage(img, 0, 0)
    
    const link = document.createElement('a')
    // link.download = `展品二维码_${exhibitionDetail.value.name || '未命名'}.png`
    link.download = exhibitionDetail.value.itemNumber
    link.href = canvas.toDataURL('image/png')
    link.click()
  }

  img.src = 'data:image/svg+xml;base64,' + btoa(unescape(encodeURIComponent(svgStr)))
  // try {
  //   if (!exhibitionDetail.value?.id) {
  //     ElMessage.warning('展品信息加载中，请稍候...')
  //     return
  //   }

  //   // 使用与页面显示相同的二维码内容
  //   const qrContent = qrValue.value
  //   console.log('生成二维码内容:', qrContent)

  //   // 创建临时canvas元素
  //   const canvas = document.createElement('canvas')
  //   const size = 300
  //   canvas.width = size
  //   canvas.height = size
    
  //   // 动态导入qrcode库
  //   import('qrcode').then(QRCode => {
  //     QRCode.toCanvas(canvas, qrContent, {
  //       width: size,
  //       margin: 2,
  //       color: {
  //         dark: '#000000',
  //         light: '#FFFFFF'
  //       },
  //       errorCorrectionLevel: 'H'
  //     }).then(() => {
  //       // 使用与页面显示完全相同的中心图标
  //       const centerText = String((exhibitionDetail.value as any)?.itemNumber || '')
  //       if (centerText) {
  //         // 复用generateCenterTextImage函数生成与页面完全相同的图标
  //         const centerIconSrc = generateCenterTextImage(centerText, 100, 100)
          
  //         // 创建图片对象并绘制到中心位置
  //         const img = new Image()
  //         img.onload = () => {
  //           const ctx = canvas.getContext('2d')
  //           if (ctx) {
  //             // 计算居中位置
  //             const centerX = (size - 100) / 2
  //             const centerY = (size - 100) / 2
              
  //             // 绘制中心图标
  //             ctx.drawImage(img, centerX, centerY, 100, 100)
  //           }
            
  //           // 下载图片
  //           const dataURL = canvas.toDataURL('image/png')
  //           const link = document.createElement('a')
  //           const fileName = `展品二维码_${exhibitionDetail.value.name || exhibitionDetail.value.itemNumber || '未命名'}.png`
  //           link.download = fileName
  //           link.href = dataURL
  //           link.style.display = 'none'
  //           document.body.appendChild(link)
  //           link.click()
  //           document.body.removeChild(link)
            
  //           ElMessage.success(`二维码「${exhibitionDetail.value.name}」下载成功`)
  //         }
          
  //         img.onerror = () => {
  //           // 如果图标加载失败，使用备用方案
  //           console.error('中心图标加载失败')
  //           downloadWithoutCenterIcon()
  //         }
          
  //         img.src = centerIconSrc
  //       } else {
  //         // 没有中心文字，直接下载
  //         downloadWithoutCenterIcon()
  //       }
        
  //       function downloadWithoutCenterIcon() {
  //         const dataURL = canvas.toDataURL('image/png')
  //         const link = document.createElement('a')
  //         const fileName = `展品二维码_${exhibitionDetail.value.name || exhibitionDetail.value.itemNumber || '未命名'}.png`
  //         link.download = fileName
  //         link.href = dataURL
  //         link.style.display = 'none'
  //         document.body.appendChild(link)
  //         link.click()
  //         document.body.removeChild(link)
          
  //         ElMessage.success(`二维码「${exhibitionDetail.value.name}」下载成功`)
  //       }
        
  //     }).catch(error => {
  //       console.error('二维码生成失败:', error)
  //       ElMessage.error('二维码生成失败，请重试')
  //     })
  //   }).catch(error => {
  //     console.error('加载qrcode库失败:', error)
  //     ElMessage.error('二维码功能加载失败')
  //   })
    
  // } catch (error) {
  //   console.error('下载二维码失败:', error)
  //   ElMessage.error('下载失败，请刷新页面重试')
  // }
}

onMounted(() => {
  getExhibitionDetail()
})
</script>

<style lang="scss" scoped>
.exhibition-detail {
  .image-error-slot {
    display: flex;
    justify-content: center;
    align-items: center;
    width: 100%;
    height: 100%;
    background-color: var(--el-fill-color-light);
    color: var(--el-text-color-secondary);
    font-size: 30px;
  }

  .carousel-container {
    :deep(.el-carousel__item) {
      border-radius: 8px;
    }
  }

  .gallery-thumbnail {
    aspect-ratio: 1;
    object-fit: cover;
  }

  .audio-guide {
    audio {
      &::-webkit-media-controls-panel {
        background-color: var(--el-color-primary-light-9);
      }
    }
  }
}
</style>